package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.AgentAddInfo;
import com.eeepay.eeepay_v2.model.BankInfo;
import com.eeepay.eeepay_v2.util.AllUtils;
import com.eeepay.eeepay_v2.util.CardTools;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.view.AreaSelectView;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABAppUtil;
import com.eeepay.v2_library.util.ABRegUtil;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.LeftRightText;
import com.eeepay.v2_library.view.TitleBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.AddAgentProto;
import cn.eeepay.api.grpc.nano.AddAgentServiceGrpc;
import cn.eeepay.api.grpc.nano.MerAddModular;
import cn.eeepay.api.grpc.nano.MerAddServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

/**
 * Created by Ching on 2017/2/27.
 * 新增代理商第二步 --- 结算信息
 */

public class AgentAddStep2 extends ABBaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, TitleBar.LeftBtnOnClickListener {

    private TitleBar titleBar;
    private LabelEditText nameLet, noLet, idNoLet;
    private LeftRightText bankLrt, areaLrt, zhLrt;
    private RadioGroup radioGroup;
    private Button nextBtn;
    private AreaSelectView areaPopView;

    private String accountType, bankArea, accountNo, province, city;
    private final int BANK = 0, ZH = 1, BASE = 2;
    private final int SAVE = 0, LOAD = 1;
    private AgentAddInfo addInfo;
    private List<BankInfo> bankList;
    private BankInfo bankInfo;
    private Bundle mBundle;
    private String cnapsNo;
//    private boolean isNext = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_add_step_2;
    }

    @Override
    protected void initWidget() {

        titleBar = getViewById(R.id.titleBar);
        nameLet = getViewById(R.id.let_open_name);
        noLet = getViewById(R.id.let_open_number);
        idNoLet = getViewById(R.id.let_id_number);
        bankLrt = getViewById(R.id.lrt_open_bank);
        areaLrt = getViewById(R.id.lrt_open_area);
        zhLrt = getViewById(R.id.lrt_open_zh);
        nameLet.setFilter(10);
        noLet.setFilter(19);
        idNoLet.setFilter(18);
//        idNoLet.setInputType(InputType.TYPE_CLASS_TEXT);
        radioGroup = getViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(this);
        radioGroup.getChildAt(0).performClick();
        nextBtn = getViewById(R.id.btn_next);

        areaPopView = new AreaSelectView(mContext);
        areaPopView.setOnAreaSelectedListener(new AreaSelectView.OnAreaSelectedListener() {
            @Override
            public void onSelected(String area) {
                bankArea = area;
                areaLrt.setRightText(area);
                areaLrt.setRightTextColor(R.color.titlebar_title_txt_color);
                city = areaPopView.getCitySelected().substring(0, areaPopView.getCitySelected().length() - 1);
                province = areaPopView.getProvinceSelected();
                areaPopView.dismiss();
            }
        });

    }

    @Override
    protected void eventOnClick() {

        titleBar.setLeftOnClickListener(this);
        bankLrt.setOnClickListener(this);
        areaLrt.setOnClickListener(this);
        zhLrt.setOnClickListener(this);
        nextBtn.setOnClickListener(this);

//        /** 模拟 **/
//        nameLet.setEditContent("李景清");
//        noLet.setEditContent("6217007200036018821");
//        idNoLet.setEditContent("445222199107282252");
//        bankLrt.setRightText("建设银行");

        saveOrLoad(LOAD);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lrt_open_bank:
                if (!CardTools.getInstance().isBankCardNo(noLet.getEditContent())) {
                    showToast("请输入有效的银行卡号");
                    return;
                }
                accountNo = noLet.getEditContent();
                sendHttpRequest(BANK);
                break;
            case R.id.lrt_open_area:
                ABAppUtil.hideSoftInput(this);
                if (areaPopView == null) {
                    areaPopView = new AreaSelectView(mContext);
                }
                areaPopView.showAtLocation(areaLrt, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.lrt_open_zh:
                if (!CardTools.getInstance().isBankCardNo(noLet.getEditContent())) {
                    showToast("请输入有效的银行卡号");
                    return;
                }
                if (TextUtils.isEmpty(city)) {
                    showToast("请选择城市");
                    return;
                }
                accountNo = noLet.getEditContent();
                sendHttpRequest(ZH);
                break;
            case R.id.btn_next:
                if (TextUtils.isEmpty(nameLet.getEditContent())) {
                    showToast("请输入开户名称");
                    return;
                } else if (!ABRegUtil.isRegiest(nameLet.getEditContent(), Constant.MER_NAME_REGEX)
                        || ABRegUtil.isRegiest(nameLet.getEditContent(), Constant.NUM_LET_REGEX)) {
                    showToast(mContext.getResources().getString(R.string.mer_name_rex));
                    return;
                }
                if (CardTools.getInstance().checkCard(idNoLet.getEditContent())) {
                    showToast("请填写有效的身份证号");
                    return;
                }
                if (!CardTools.getInstance().isBankCardNo(noLet.getEditContent())) {
                    showToast("请输入有效的银行卡号");
                    return;
                }
                if (TextUtils.isEmpty(areaLrt.getRighText()) || TextUtils.isEmpty(bankArea)) {
                    showToast("请选择开户地区");
                    return;
                }
                if (TextUtils.isEmpty(cnapsNo)) {
                    showToast("请选择开户支行");
                    return;
                }
                accountNo = noLet.getEditContent();
                if (TextUtils.isEmpty(bankLrt.getRighText()) || TextUtils.isEmpty(zhLrt.getRighText())) {
                    showToast("请获取开户银行和开户支行");
                    return;
                }
                sendHttpRequest(BASE);
                break;
        }
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();//Constant.URL.URL Constant.URL.PORT
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            //        GrpcUtils.getInstance().doGrpcTask("192.168.4.4", "8090", taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                synchronized (this) {
                    if (channel.isShutdown() || channel.isTerminated()) {
                        channel = ManagedChannelBuilder.forAddress(Constant.URL.URL,
                                Integer.parseInt(Constant.URL.PORT)).usePlaintext(true).build();
                    }
                }
                switch (taskId) {
                    case BANK:/**校验结算卡获取开户行**/
                        MerAddServiceGrpc.MerAddServiceBlockingStub stub = MerAddServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(20, TimeUnit.SECONDS);
                        MerAddModular.AccountNoReq accReq = new MerAddModular.AccountNoReq();
                        accReq.settleAccountNo = accountNo;
                        return stub.checkSettleAccountNo(accReq);
                    case ZH:/**获取支行信息**/
                        MerAddServiceGrpc.MerAddServiceBlockingStub zhStub = MerAddServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(20, TimeUnit.SECONDS);
                        MerAddModular.BankAndCnapReq bankReq = new MerAddModular.BankAndCnapReq();
                        bankReq.accountNo = accountNo;
                        bankReq.cityName = city;
                        return zhStub.getBankAndCnap(bankReq);
                    case BASE:
                        AddAgentServiceGrpc.AddAgentServiceBlockingStub baseStub = AddAgentServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(20, TimeUnit.SECONDS);
                        AddAgentProto.AgentBaseInfoReq baseReq = new AddAgentProto.AgentBaseInfoReq();
                        baseReq.accountName = nameLet.getEditContent();
                        baseReq.accountNo = accountNo;
                        baseReq.idCardNo = idNoLet.getEditContent();
                        baseReq.mobilephone = addInfo.getPhone();
                        return baseStub.baseInfoCheck(baseReq);
                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null)
                    return;
                switch (taskId) {
                    case BANK:/**校验结算卡获取开户行**/
                        MerAddModular.BankNameRes bankNameRes = (MerAddModular.BankNameRes) result;
                        if (!bankNameRes.resMsg.status) {
                            showToast(bankNameRes.resMsg.msg);
                        } else {
                            bankLrt.setRightText(bankNameRes.bankName);
                        }
                        break;
                    case ZH:
                        MerAddModular.BankAndCnapRes bankCnapRes = (MerAddModular.BankAndCnapRes) result;
                        if (bankList != null && bankList.size() > 0)
                            bankList.clear();
                        if (!bankCnapRes.resMsg.status) {//查询失败
                            showToast(bankCnapRes.resMsg.msg);
                        } else {
                            MerAddModular.CnapInfo[] cnapInfo = bankCnapRes.cnapInfo;
                            BankInfo bankInfo;
                            bankList = new ArrayList<>();
                            for (MerAddModular.CnapInfo cnap : cnapInfo) {
                                bankInfo = new BankInfo(cnap.bankName, cnap.cnapsNo);
                                bankList.add(bankInfo);
                            }
                            if (bankList != null && bankList.size() > 0) {
                                mBundle = new Bundle();
                                mBundle.putSerializable(Constant.KEY_LIST,
                                        (Serializable) bankList);
                                goActivityForResult(SelectBankActivity.class, mBundle, Constant.RESULTCODE_100);
                            }
                        }
                        break;
                    case BASE:
                        AddAgentProto.AgentBaseInfoRes baseInfoRes = (AddAgentProto.AgentBaseInfoRes) result;
                        if (!baseInfoRes.resMsg.status) {
                            showToast(baseInfoRes.resMsg.msg);
                            return;
                        }
                        saveOrLoad(SAVE);
                        AllUtils.addActivity(AgentAddStep2.this);
                        goActivity(AgentAddStep3.class);
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        bankInfo = (BankInfo) data.getSerializableExtra(Constant.TAG);
        if (bankInfo != null) {
            zhLrt.setRightTextColor(bankInfo.getBank_name(), R.color.gray_text_color);
            cnapsNo = bankInfo.getCnaps_no();
        }
    }

    public void saveOrLoad(int type) {
        switch (type) {
            case SAVE://保存
                if (addInfo == null)
                    addInfo = SPUtils.getAgentAddInfo();
                addInfo.setAccountName(nameLet.getEditContent());
                addInfo.setAccountType(accountType);
                addInfo.setAccountNo(noLet.getEditContent());
                addInfo.setIdNo(idNoLet.getEditContent());
                addInfo.setBankName(bankLrt.getRighText());
                addInfo.setAccount_province(province);
                addInfo.setAccount_city(city);
                addInfo.setZh(zhLrt.getRighText());
                addInfo.setCnapsNo(cnapsNo);
                addInfo.setZhArea(bankArea);
                SPUtils.saveAgentAddInfo(addInfo);
                break;
            case LOAD://加载
                addInfo = SPUtils.getAgentAddInfo();
                LogUtils.d(" addInfo = " + addInfo.toString());
                nameLet.setEditContent(addInfo.getAccountName());
                if ("对公".equals(addInfo.getAccountType())) {
                    radioGroup.getChildAt(0).performClick();
                } else {
                    radioGroup.getChildAt(1).performClick();
                }
                noLet.setEditContent(addInfo.getAccountNo());
                idNoLet.setEditContent(addInfo.getIdNo());
                bankLrt.setRightText(addInfo.getBankName());
                areaLrt.setRightText(addInfo.getZhArea());
                areaLrt.setRightTextColor(R.color.titlebar_title_txt_color);
                zhLrt.setRightText(addInfo.getZh());
                cnapsNo = addInfo.getCnapsNo();
                province = addInfo.getAccount_province();
                city = addInfo.getAccount_city();
                bankArea = addInfo.getZhArea();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_bis_public:
                accountType = "对公";
                break;
            case R.id.rbtn_person_private:
                accountType = "对私";
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            saveOrLoad(SAVE);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLeftClick(View view) {
        saveOrLoad(SAVE);
        finish();
    }
}
